package com.itrip.itriosearch.controller;


import com.itrip.common.vo.UserVo;
import com.itrip.itriosearch.entity.User;
import com.itrip.itriosearch.service.UserService;
import com.itrip.itriosearch.util.*;
import com.itrip.itriosearch.vo.ItripTokenVO;
import com.itrip.itriosearch.vo.UserVO;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;
import java.util.regex.Pattern;

import static com.itrip.itriosearch.util.JwtUtil.TOKEN_EXP;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author 四阶段项目二组
 * @since 2020-02-25
 */
@CrossOrigin //跨域
@RestController
@RequestMapping("/auth/api")
public class UserController {


    @Autowired
    UserService userService;

    @Resource
    private RedisUtil redisUtil;

    @PostMapping("/dologin")
    @ApiOperation(value = "用户登录")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form", required = true, value = "用户名", name = "name", defaultValue = "3093546660@qq.com"),
            @ApiImplicitParam(paramType = "form", required = true, value = "密码", name = "password", defaultValue = "123456"),
    })
    public Dto login(
            @RequestParam
                    String name,
            @RequestParam
                    String password) {
        if (((!"".equals(name)) || (null != name)) && ((!"".equals(password)) || (null != password))) {
            User SysUser = new User();
            SysUser.setUserName(name);
            String pwd = SHAUtils.encodeData(password);
            SysUser.setUserPassword(pwd);
            User user = userService.login(SysUser);
            if (user != null) {
                String token = JwtUtil.getToken(SysUser.getUserName());
                System.out.println(token);
                //返回TokenVO
                ItripTokenVO tokenVO = new ItripTokenVO(token,
                        Calendar.getInstance().getTimeInMillis() + TOKEN_EXP,//2h有效期
                        Calendar.getInstance().getTimeInMillis());
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                redisUtil.set(token, userVo, 7200);
                return DtoUtil.returnSuccess("成功",tokenVO);
            }
        }

        return DtoUtil.returnFail("账号或者密码错误", "10202");
    }


    @ApiOperation(value = "用户注销", httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "客户端需在header中发送token")
    @ApiImplicitParam(paramType = "header", required = true, name = "token", value = "用户认证凭据", defaultValue = "PC-yao.liu2015@bdqn.cn-8-20170516141821-d4f514")
    @RequestMapping(value = "/logout", method = RequestMethod.GET, produces = "application/json", headers = "token")
    public @ResponseBody
    Dto logout(HttpServletRequest request) {
//验证token
        String token = request.getHeader("token");
        System.out.println(token);
        if (token == null) {
            return DtoUtil.returnFail("token无效", ErrorCode.AUTH_TOKEN_INVALID);
        }
//验证token
        try {
            Claims claims = JwtUtil.checkToken(token);
            System.out.println(claims);
            claims.remove(claims.getSubject());
            redisUtil.del(token);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("token无效", ErrorCode.AUTH_TOKEN_INVALID);
        }
        return DtoUtil.returnSuccess("注销成功");
    }


    /**
     * 检查用户是否已注册
     *
     * @param name
     * @return
     */
    @ApiOperation(value = "用户名验证", httpMethod = "GET",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "验证是否已存在该用户名")
    @RequestMapping(value = "/ckusr", method = RequestMethod.GET, produces = "application/json")
    public @ResponseBody
    Dto checkUser(
            @ApiParam(name = "name", value = "被检查的用户名", defaultValue = "test@bdqn.cn")
            @RequestParam String name) {
        if (name != null || name.equals("")) {
            User user = userService.findByUsername(name);
            if (user != null) {
                System.out.println(user.toString());
                return DtoUtil.returnFail("用户已存在，注册失败", ErrorCode.AUTH_USER_ALREADY_EXISTS);
            } else {
                return DtoUtil.returnSuccess("用户名可用");
            }
        } else {
            return DtoUtil.returnFail("用户名为空", ErrorCode.AUTH_UNKNOWN);
        }

    }

    /**
     * 使用邮箱注册
     *
     * @param userVO
     * @return
     */
    @ApiOperation(value = "使用邮箱注册", httpMethod = "POST",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "使用邮箱注册 ")
    @RequestMapping(value = "/doregister", method = RequestMethod.POST, produces = "application/json")
    public @ResponseBody
    Dto doRegister(
            @ApiParam(name = "userVO", value = "用户实体", required = true)
            @RequestBody UserVO userVO) {
        if (!validEmail(userVO.getUserCode()))
            return DtoUtil.returnFail("请使用正确的邮箱地址注册", ErrorCode.AUTH_ILLEGAL_USERCODE);
        try {
            User user = new User();
            user.setUserCode(userVO.getUserCode());
            user.setUserName(userVO.getUserName());
            user.setUserPassword(SHAUtils.encodeData(userVO.getUserPassword()));
            user.setUserType(0);
            user.setActivated(0);
            boolean bool = userService.insertUser(user);
            if (bool == true) {
                return DtoUtil.returnSuccess();
            } else {
                return DtoUtil.returnFail("注册失败", ErrorCode.AUTH_UNKNOWN);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail(e.getMessage(), ErrorCode.AUTH_UNKNOWN);
        }
    }

    @ApiOperation(value = "邮箱注册用户激活", httpMethod = "PUT",
            protocols = "HTTP", produces = "application/json",
            response = Dto.class, notes = "邮箱激活")
    @RequestMapping(value = "/activate", method = RequestMethod.PUT, produces = "application/json")
    public @ResponseBody
    Dto activate(
            @ApiParam(name = "user", value = "注册邮箱地址", defaultValue = "test@bdqn.cn")
            @RequestParam String user,
            @ApiParam(name = "code", value = "激活码", defaultValue = "018f9a8b2381839ee6f40ab2207c0cfe")
            @RequestParam String code) {
        //判断返回的验证信息
        int judge = userService.emailTheActivation(user, code);
        System.out.println(judge);
        //匹配返回1，用户不存在返回2，验证码错误返回3
        switch (judge) {
            case 1:
                System.out.println(judge);
                return DtoUtil.returnSuccess("激活成功");
            case 2:
                System.out.println(judge);
                return DtoUtil.returnFail("激活失败", ErrorCode.AUTH_ACTIVATE_FAILED);
            case 3:
                System.out.println(judge);
                return DtoUtil.returnFail("验证码错误", ErrorCode.AUTH_ACTIVATE_FAILED);
        }
        return DtoUtil.returnFail("激活失败", ErrorCode.AUTH_ACTIVATE_FAILED);
    }


    /**
     * 合法E-mail地址：
     * 1. 必须包含一个并且只有一个符号“@”
     * 2. 第一个字符不得是“@”或者“.”
     * 3. 不允许出现“@.”或者.@
     * 4. 结尾不得是字符“@”或者“.”
     * 5. 允许“@”前的字符中出现“＋”
     * 6. 不允许“＋”在最前面，或者“＋@”
     */
    private boolean validEmail(String email) {

        String regex = "^\\s*\\w+(?:\\.{0,1}[\\w-]+)*@[a-zA-Z0-9]+(?:[-.][a-zA-Z0-9]+)*\\.[a-zA-Z]+\\s*$";
        return Pattern.compile(regex).matcher(email).find();
    }



}
